<?php

namespace app\components;

use phpDocumentor\Reflection\DocBlock\Tags\Var_;

use Yii;
use yii\web\Controller;
use yii\web\Response;
use app\components\Api;
use app\components\Wechat;
use app\components\Loyalty;
use app\models\WechatLoginForm;

class BaseController extends Controller
{
    /**
     * @var string the ID of the action that is used when the action ID is not specified
     * in the request. Defaults to 'index'.
     */
    public $defaultAction = 'index';

    /**
     * @var null|string|false the name of the layout to be applied to this controller's views.
     * This property mainly affects the behavior of [[render()]].
     * Defaults to null, meaning the actual layout value should inherit that from [[module]]'s layout value.
     * If false, no layout will be applied.
     */
    public $layout = 'base';

    /**
     * 
     */
    public function init()
    {

    }
    
    /**
     * 断点调试
     * @param mix $data
     * @param boolean $break
     */
    public function bp($data, $break = true)
    {
        echo "<pre>";
        if (is_string($data)) echo $data; else print_r($data);
        echo "</pre>";
        if ($break) exit;
    }

    /**
     * use our ErrorController to display error
     * @param string $message
     **/
    public function error($message, $code = null)
    {
        $this->redirect(['errors/index', 'message' => $message, 'code' => $code]);
    }

    /**
     * set or get session value based on Yii::$app->session
     */
    public function session($key, $value = null)
    {
        $session = Yii::$app->session;

        // open session
        if (!$session->isActive) {
            $session->open();
        }

        if ($session->has($key)) {

            // return the existing key when value is null
            if (is_null($value)) {
                return $session->get($key);
            }

            // replace the old value
            $old = $session->get($key);
            if ($value != $old) {
                $session->set($key, $value);
            }
        } else {
            $session->set($key, $value);
        }
    }

    /**
     * set tenant_id in session
     * @param string $tenant_id
     */
    public function setTenantId($tenant_id)
    {
        $this->session('tenant_id', $tenant_id);
    }

    /**
     * get tenant_id in session
     */
    public function getTenantId()
    {
        return $this->session('tenant_id');
    }

    /**
     * set appid in session
     * @param string $appid
     */
    public function setAppid($appid)
    {
        $this->session('appid', $appid);
    }

    /**
     * get appid in session
     */
    public function getAppid()
    {
        return $this->session('appid');
    }

    /**
     * 把access_token放入session中
     * @param string $access_token
     */
    public function setAccessToken($access_token)
    {
        $this->session('access_token', $access_token);
    }
 
    /**
     * 通过session获取access_token
     */
    public function getAccessToken()
    {
        return $this->session('access_token');
    }

    /**
     * 把identifier放入session中
     * @param string $identifier
     */
    public function setIdentifier($identifier)
    {
        $this->session('identifier', $identifier);
    }

    /**
     * 通过session获取userinfo，如果没有则返回false
     * @return array | false
     */
    public function getIdentifier()
    {
        return $this->session('identifier');
    }

    /**
     * 重要方法!
     * 把openid放入session中，同时把 loyaltyinfo 和 wechatinfo 放入session中
     * @param string $openid
     */
    public function setOpenid($openid)
    {
        $this->session('openid', $openid);

//         $wechatInfo = Wechat::userinfo([$openid]);
//         Log::debug('WECHAT INFO', $wechatInfo);

//         if (isset($wechatInfo['subscribe'])) {
//             $this->setWechatInfo($wechatInfo);
//         } else {
            $this->setWechatInfo(false);
//         }

        $userInfo = Loyalty::customer_get(['wechat_openid' => $openid]);
//         Log::debug('LOYALTY INFO', $userInfo);

        if (isset($userInfo['status']) && $userInfo['status'] == 'success') {
        	$userInfo['code'] = $userInfo['membership']['code'];
        	$this->setUserInfo($userInfo);
        } elseif (isset($userInfo['code'])) {
            $this->setUserInfo($userInfo);
        } else {
            $this->setUserInfo(false);
        }

        // 触发用户登录
        // $model = new WechatLoginForm();
        // $model->login($openid);
    }

    /**
     * 通过session获取openid
     */
    public function getOpenid()
    {
        return $this->session('openid');
    }
    
    /**
     * 重要方法!
     * 把$vipCode放入session中，同时把 loyaltyinfo 和 wechatinfo 放入session中
     * @param string $vipCode
     */
    public function setCode($code)
    {
    	$this->session('code', $code);

    	$this->setWechatInfo(false);
    	
    	$userInfo = Loyalty::customer_get(['code' => $code]);
    	
    	if (isset($userInfo['status']) && $userInfo['status'] == 'success') {
    		$userInfo['code'] = $userInfo['membership']['code'];
    		$this->setUserInfo($userInfo);
    	} elseif (isset($userInfo['code'])) {
    		$this->setUserInfo($userInfo);
    	} else {
    		$this->setUserInfo(false);
    	}
    }
    
    /**
     * 通过session获取mobile
     */
    public function getMobile()
    {
    	return $this->session('mobile');
    }
    
    /**
     * 重要方法!
     * 把$mobile放入session中，同时把 loyaltyinfo 和 wechatinfo 放入session中
     * @param string $vipCode
     */
    public function setMobile($mobile)
    {
    	$this->session('mobile', $mobile);
    
    	$this->setWechatInfo(false);
    	 
    	$userInfo = Loyalty::customer_get(['mobile' => $mobile]);
    	 
    	if (isset($userInfo['status']) && $userInfo['status'] == 'success') {
    		$userInfo['code'] = $userInfo['membership']['code'];
    		$this->setUserInfo($userInfo);
    	} elseif (isset($userInfo['code'])) {
    		$this->setUserInfo($userInfo);
    	} else {
    		$this->setUserInfo(false);
    	}
    }
    
    /**
     * 通过session获取vipCode
     */
    public function getCode()
    {
    	return $this->session('code');
    }

    /**
     * 把userinfo放入session中
     * @param array $userInfo
     */
    public function setUserInfo($userInfo)
    {
        if (isset($userInfo['code'])) {
            $this->session('userInfo', $userInfo);
        } else {
            $this->session('userInfo', false);
        }
    }

    /**
     * 通过session获取userinfo，如果没有则返回false
     * @return array | false
     */
    public function getUserInfo()
    {
        return $this->session('userInfo');
    }

    /**
     * 把userinfo放入session中
     * @param array $userInfo
     */
    public function setWechatInfo($wechatInfo)
    {
        if (isset($wechatInfo['subscribe'])) {
            $this->session('wechatInfo', $wechatInfo);
        } else {
            $this->session('wechatInfo', false);
        }
    }

    /**
     * 通过session获取userinfo，如果没有则返回false
     * @return array | false
     */
    public function getWechatInfo()
    {
        return $this->session('wechatInfo');
    }

    /**
     * 清空seesion
     */
    public function clearAllSession()
    {
        Yii::$app->session->destroy();
    }
    
    /**
     * check customer exists
     * @param string $code
     * @param string $mobile
     * @return boolean
     */
    public function checkExists($code, $mobile)
    {
    	$re = Loyalty::customer_search(['code' => $code, 'mobile' => $mobile]);
    	if ($re['status'] == 'success') {
    		return true;
    	} else {
    		return false;
    	}
//     	echo '<pre>';print_r($re);exit;
    }

    /**
     * 发送优惠券
     * @param string $openid
     * @param string $identifier DMS的卡券identifier
     */
    public function sendCoupon($openid, $identifier)
    {
        // ------------------------------------------------------------------
        // 用户领取优惠券链接，点击后会自动跳转到自定义的地址
        // ------------------------------------------------------------------
        // http://wcapi.xgatecorp.com/wechat/wx/card/get_code?tracker=[tenant_tracker]&appid=[app_id]&identifier=[couponidentifier]&openid=[openid]&redirect=[redirect]
        // @method Get
        // @author Raymond NG

        $appid = Wechat::config('appid');
        $tracker = '350e92b9-5986-4f05-f72c-77289fac5343';
        $redirect = 'http://winshare.onthemooner.com/index.php/member/coupons';

        if (empty($openid) || empty($identifier)) {
            return false;
        }
        
        $url = 'http://wcapi.xgatecorp.com/wechat/wx/card/get_code?tracker=' . $tracker . 
                                                                    '&appid=' . $appid . 
                                                                    '&identifier=' . $identifier . 
                                                                    '&openid=' . $openid .
                                                                    '&redirect=' . $redirect;
        $re = file_get_contents($url);
        Log::debug('redirect的字符串长度', strlen($re));
        if (strlen($re) > 263) {
            return true;
        }
    }

}
